﻿using System;
using Microsoft.Xna.Framework;
using Map;

namespace Map_Creator.MapInfo
{
    public class CustomDataGrid : CustomDataGridStruct
    {
        public ExtendedTreeNode Node;

        public Map AssociatedMap
        {
            get { return (Map)Map; }
            set { Map = value; }
        }

        public TileSet AssociatedTileSet
        {
            get { return (TileSet)TileSet; }
            set { TileSet = value; }
        }   

        public object this[int x, int y]
        {
            get { return Data.GetValue(x, y); }
            set { Data.SetValue(value, x, y); }
        }

        public CustomDataGrid(Type type, Point size, int ID = 0) : base(ID)
        {
            DataType = type;
            GridSize = size;
            Data = Array.CreateInstance(type, GridSize.X, GridSize.Y);
        }

        public object NextValue(object value)
        {
            if (DataType == typeof(int))
            {
                var valAsInt = value is int ? (int)value : 0;
                return (valAsInt + 1) % 10;
            }

            if (DataType == typeof(bool))
            {
                var valAsBool = value is bool && (bool)value;
                return !valAsBool;
            }
            return null;
        }

        public override void Delete()
        {
            if (AssociatedMap == null) return;

            if (AssociatedTileSet != null)
            {
                AssociatedTileSet.DataGrids.Remove(this);

                AssociatedTileSet.DataGridCount--;

                if (AssociatedTileSet.CurrentDataGrid == this)
                    AssociatedTileSet.CurrentDataGrid = null;
            }
            else
            {
                AssociatedMap.DataGrids.Remove(this);

                AssociatedMap.DataGridCount--;

                if (AssociatedMap.CurrentDataGrid == this)
                    AssociatedMap.CurrentDataGrid = null;
            }

            var parent = Node.Parent;
            Node.Remove();
            if (parent.Nodes.Count == 0)
                parent.Remove();

            // set null associated map so remove wont ever happen twice :O
            AssociatedMap = null;
            AssociatedTileSet = null;

            base.Delete();
        }
    }
}